<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Image;
use Think\Page;
use Org\Net\Http;
class FoodController extends AuthController{
	public function food_gallery(){
		$this->food=1;
		$this->foodIndex=1;
		$this->display();
	}
	public function index(){
		$Food=D('FoodView');
		$list = $Food->group('id')->order(array('id'=>'desc'))->select();
// 		$type = S("FoodType");
// 		if(!$type){
// 			$type = D("FoodType")->cache("FoodType")->order(array('id'=>'asc'))->select();
// 		}
		$type = D("FoodType")->order(array('id'=>'asc'))->select();
// 		$unit = S("unit");
// 		if(!$unit){
// 			$unit = D("unit")->cache("unit")->order(array('id'=>'asc'))->select();
// 		}
		$unit = D("unit")->order(array('id'=>'asc'))->select();
		$this->assign('list',$list);
// 		var_dump($list);
		$this->assign('type',$type);
		$this->assign('unit',$unit);
		$this->display();
	}
	/**
	 * 修改食物类型
	 */
	public function UpdateFoodCategory(){
		$id = I("id");
		$where['id'] = $id;
		$result = M("FoodCategory")->where($where)->save($_POST);
		$this->ajaxReturn($result);
	}
	/**
	 * 添加食物类型
	 */
	public function addFoodCategory(){
		$result = M("FoodCategory")->add($_POST);
		$this->ajaxReturn($result);
	}
	/**
	 * 删除食物类型
	 */
	public function delFoodCategory(){
		$id = I("id");
		$where['id'] = $id;
		$result = M("FoodCategory")->where($where)->delete();
		$this->ajaxReturn($result);
	}
	/**
	 * 获取食物类型
	 */
	public function getFoodCategory(){
		$fid = I("fid");
		$where['fid'] = $fid;
		$list = M("FoodCategory")->where($where)->select();
		$this->ajaxReturn($list);
	}
	public function getFoodTag(){
		$type = I('type');
		if($type!=null&&$type!=""){
			$tag = M('FoodTag')->where(array('food_type'=>$type))->select();
			$this->ajaxReturn($tag);
		}
	}
	public function getInfo(){
		$id = I('id');
		if(isset($id)){
			$info=D("Food")->relation(true)->where(array('id'=>$id))->find();
			$this->ajaxReturn($info,'json');
		}
	}
	public function editFood(){
		if(IS_POST){
			$file = $_FILES['fileField'];
			if($file['size']>0){
				$uploadpath = "Public/Upload/Food/";//上传路径
				if (!file_exists($uploadpath)){
					mkdir($uploadpath, 0777);
				}
				$pinfo = pathinfo($file['name']);
				$ftype = $pinfo['extension'];//文件类型
				$name = basename($file['name'],".{$ftype}");
					
				$fileName = md5($name.time()).".".$ftype;//识别图
				$image = new Image();
				$image->open($file['tmp_name']);
				$image->save($uploadpath.$fileName);
				$imgurl = 'http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__.'/'.$uploadpath.$fileName;
			}else{
				$imgurl=M('Food')->where(array('id'=>I('id')))->getField('food_image');
			}
			$data = array(
					'food_name'	=> I('name'),
					'type'  => I('type'),
// 					'price'  => I('price'),
// 					'yprice'  => I('yprice'),
// 					'unit'    => I('unit'),
					'introduce'	=> I('introduce'),
					'food_tag'=>I('tag'),
					'food_image'=>$imgurl
			);
			$Food = D('Food');
			$fid = I('id');
			if($Food->create($data)){
				$result=$Food->where(array('id'=>$fid))->save($data);
				/* M('FoodCategory')->where(array('fid'=>$fid))->delete();
				$category = I("category");
				$price    = I("price");
				$yprice   = I("yprice");
				$unit     = I("unit");
				$count = count($category);
				for($i = 0;$i<$count;$i++){
					$category_item = array(
							'fid'      =>$fid,
							'title'    =>$category[$i],
							'price'    =>$price[$i],
							'yprice'   =>$yprice[$i],
							'unit'     =>$unit[$i],
					);
					$category_data[] = $category_item;
				}
				$result2 = M("FoodCategory")->addAll($category_data); */
				if($result){
					$this->success("修改成功","index");
				}else{
					$this->error("修改失败");
				}
			}else{
				$this->error($Food->getError());
			}
		}
	}
	
	public function addFood(){
		if(IS_POST){
			$file = $_FILES['fileField'];
			if($file['size']>0){
				$uploadpath = "Public/Upload/Food/";//上传路径
				if (!file_exists($uploadpath)){
					mkdir($uploadpath, 0777);
				}
				$pinfo = pathinfo($file['name']);
				$ftype = $pinfo['extension'];//文件类型
				$name = basename($file['name'],".{$ftype}");
					
				$fileName = md5($name.time()).".".$ftype;//识别图
				$image = new Image();
				$image->open($file['tmp_name']);
				$image->save($uploadpath.$fileName);
				$imgurl = 'http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__.'/'.$uploadpath.$fileName;
			}
			$data = array(
					'food_name'	=> I('name'),
					'type'  => I('type'),
// 					'price'  => I('price'),
// 					'yprice'  => I('yprice'),
// 					'unit'    => I('unit'),
					'introduce'	=> I('introduce'),
					'food_tag'=>I('tag'),
					'food_image'=>$imgurl
			);
			$Food = D('Food');
			$data = $Food->create($data);
			if($data){
// 				$data["FoodCategory"] = $category_data;
				$result=$Food->add($data);
				if($result){
					$category = I("category");
					$price    = I("price");
					$yprice   = I("yprice");
					$unit     = I("unit");
					$count = count($category);
					for($i = 0;$i<$count;$i++){
						$category_data[] = array(
								'fid'      =>$result,
								'title'    =>$category[$i],
								'price'    =>$price[$i],
								'yprice'   =>$yprice[$i],
								'unit'     =>$unit[$i],
						);
					}
					M("FoodCategory")->addAll($category_data);
					$this->success("添加成功","index");
				}else{
					$this->error("添加失败");
				}
			}else{
				$this->error($Food->getError());
			}		
		}
	}


	//食品excel导入
	    public function upload() {
        header("Content-Type:text/html;charset=utf-8");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->autoSub =  false;
        $upload->replace  =  true; //存在同名是否覆盖
        $upload->exts      =     array('xls', 'xlsx');// 设置附件上传类
        $upload->saveName =  'food';
        $upload->rootPath = 'Public/Upload/Excel/';
        // 上传文件
        $info   =   $upload->uploadOne($_FILES['excelData']);
        $filename = 'Public/Upload/Excel/'.$info['savename'];
        $exts = $info['ext'];
        if(!$info) {// 上传错误提示错误信息
              $this->error($upload->getError());
          }else{// 上传成功
                  $this->goods_import($filename, $exts);
        }
    }

    	    //导入数据方法
    public function goods_import($filename,$exts='xlsx')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }


        //载入文件
        $PHPExcel=$PHPReader->load($filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=1;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $data[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
            }

        }
       $this->save_import($data);
    }

    public function save_import($data){
    	$Food = D('Food');
    	foreach($data as $k => $v){
    		$foodData = array(
    			'food_name' =>$v['A'],
    			'type'		=>$v['B'],
    			'yprice'    =>$v['C'],
    			'price'     =>$v['D'],
    			'unit'		=>$v['E'],
    			'introduce' =>$v['F'],
    			'food_image'=>$v['G'],
    			'food_tag'	=>$v['H'],
    		);
    		if($Food->create($foodData)){
    			$Food->add();
    		}
    	}
    	$this->success('添加成功！');
    }

    //导出excel
        public function goods_export() {
        //print_r($goods_list);exit;
        $goods_list = M('Food')->select();
        $data = array();
        foreach ($goods_list as $k=>$goods_info){
            $data[$k][food_name] = $goods_info['food_name'];
            $data[$k][type] = $goods_info['type'];
            $data[$k][yprice] = $goods_info['yprice'];
            $data[$k][price]  = $goods_info['price'];
            $data[$k][unit]  = $goods_info['unit'];
            $data[$k][introduce]  = $goods_info['introduce'];
            $data[$k][food_image] = $goods_info['food_image'];
            $data[$k][ctime] = date("Y-m-d H:i:s",$goods_info['ctime']);
        }

        //print_r($goods_list);
        //print_r($data);exit;

        foreach ($data as $field=>$v){

            if($field == 'food_name'){
                $headArr[]='名称';
            }

            if($field == 'type'){
                $headArr[]='类型';
            }

            if($field == 'yprice'){
                $headArr[]='原价';
            }

            if($field == 'price'){
                $headArr[]='单价';
            }

            if($field == 'unit'){
                $headArr[]='单位';
            }

            if($field == 'introduce'){
                $headArr[]='简介';
            }
            if($field == 'food_image'){
                $headArr[]='图片地址';
            }

            if($field == 'ctime'){
                $headArr[]='创建时间';
            }
        }

        $filename="goods_list";

        $this->getExcel($filename,$headArr,$data);
    }

        private  function getExcel($fileName,$headArr,$data){
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
}